<?php
defined('_JEXEC') or die('Restricted access'); 
 
jimport( 'joomla.html.html.tabs' );
JHtml::_('jquery.framework');
JHtml::_('behavior.keepalive');
JHTML::_('behavior.tooltip'); 
JHtml::_('behavior.framework');
JHTML::_('behavior.modal');	

$user = &JFactory::getUser();
?>

<style>
    table.adminlist tbody tr td { padding: 5px 8px; }
    table.adminlist thead th { padding: 5px 8px; }
    .print-redemption { border:1px solid #CCC; border-width:1px 0 0 1px; }
    .print-redemption-label, .print-redemption-value { border:1px solid #CCC; border-width:0 1px 1px 0; padding: 5px 8px; }
    .print-redemption-label { font-weight: bold;  }
    .product-redemption-label, .product-redemption-value { border:1px solid #CCC; border-width:0 1px 1px 0; padding: 4px 8px; text-align: left; }
</style>

<script type="text/javascript" src="<?php echo JURI::root();?>js/jquery.js"></script>
<!-- Date picker -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<link href="<?php echo JURI::root();?>administrator/components/com_wrd/assets/css/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="<?php echo JURI::root();?>administrator/components/com_wrd/assets/js/jquery-ui-1.9.2.custom.js"></script>
<!--End -->
<script type="text/javascript" src="<?php echo JURI::root();?>js/json_encode.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo JURI::root();?>js/multiselect/jquery-ui.css" />
<link type="text/css" href="<?php echo JURI::root();?>css/buttons.css" rel="stylesheet" />
<script type="text/javascript" src="<?php echo JURI::root();?>js/dialog/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
    
	jQuery(function() {
			jQuery('.datepicker').datepicker( {
				onSelect: function(date) {
					var to = <?php echo count($this->models); ?>;
					var j = jQuery(this).attr('rel');
					//alert(k);
					for(i = j; i <= to; i++){
						jQuery("#datepicker"+i).val(date);	
					}
				},
				showOn: "button",
				buttonImage: "<?php echo JURI::root();?>administrator/components/com_wrd/assets/images/calendar24x24.png",
				buttonImageOnly: true,
				dateFormat: "d-m-yy",
			});
			
			
			
	});
	
	function checkStatus(){
		
		var approved = <?php echo $this->models[0]->approved; ?>;
		if(approved != 9){
			jQuery('#adminForm').submit();
			return true;
		}
		else if(approved == 9){
			
			alert("Redemption has been deleted");
			return false;
		}
		return false;
	}
	
	function updateVoucherList(rel){
			
			var rel = parseInt(rel);			
			var indexval = '';
			var preval = jQuery('#product_list_'+rel+'_voucher').val()
		
			var arr_voucher = jQuery('#voucher_id').val().split(',');
			var quality = arr_voucher.length -1;
			
			
			for(var index=0; index<quality; index++) {
               var indexrel = parseInt(''+jQuery('#product_list_'+arr_voucher[index]+'_voucher').attr('rel'));
               if(indexrel > rel){
					indexval = countingSequense(indexval == '' ? preval : indexval);
					jQuery('#product_list_'+arr_voucher[index]+'_voucher').val(indexval);
				}
            }
		}
		
		function countingSequense(input){
			var output = '';
			var arr_out = input.split("");
			var arr_len = arr_out.length-1;
			var owe = 1;

			if(isNaN(arr_out[arr_len])){
				return output;
			}
			
			for(var i = arr_len; i >=0; i--) {
				
				if(!isNaN(arr_out[i])){
					
					arr_out[i]=parseInt(arr_out[i])+owe;
					owe = 0;
					if(arr_out[i] == 10){
						if(!isNaN(arr_out[i-1])){
							arr_out[i] = 0;
							owe = 1;
						}
					}
				}
				
			}
			
			for(var i = 0 ; i <= arr_len; i++) {
				output = output + arr_out[i];
			}
			
			//console.log(output);
			return output;
		}
		
	//<![CDATA[
    Joomla.submitbutton = function(pressbutton){
        if (pressbutton == 'redirect_to_profile' || pressbutton == 'products_page') {
            submitform( pressbutton );
            return;
        }
        if (pressbutton == 'save_new_redemption') {
            if (document.adminForm.cat_id.value == 0) {
                alert( 'Please select a category !' );
                document.adminForm.cat_id.focus();
                return false;
            }
            if (document.adminForm.quantity.value == '') {
                alert( 'Must have quantity !' );
                document.adminForm.quantity.focus();
                return false;
            }
            if (isNaN(document.adminForm.quantity.value)) {
                alert( 'Quantity have to a number !' );
                document.adminForm.quantity.focus();
                return false;
            }
            submitform( pressbutton );
        }
    }
    jQuery.noConflict();
</script>
<script>
	jQuery(document).ready(function(){
		jQuery('.viewdetailredemption').click(function(){
			var this_id = jQuery(this).attr('id');
			jQuery('.'+this_id).toggle();
			
		});
	});
</script>

<form action="<?php echo JRoute::_("index.php?option=com_wrd&controller=profile")?>" method="post" name="adminForm" id="adminForm" >
    <div class="col width-60" style="float:left; width:75%">
        <fieldset class="adminform">
            <legend><?php echo JText::_('Details')?></legend>
            <table class="print-redemption" cellpadding="0" cellspacing="0" style="width: 100%; margin: 20px 0;">
                <tbody>
                    <tr valign="top">
                        <td class="print-redemption-label" style="width: 23%;">Guest Name:</td>
                        <td class="print-redemption-value"><?php echo $this->user->l_name.' '.$this->user->f_name; ?></td>
                    </tr>                    
                    <tr>
						<td class="print-redemption-label">Redemption Code:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->code; ?></td>
					</tr>
					<tr>
						<td class="print-redemption-label">Outlet pick up:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->outlet; ?></td>
					</tr>
					<tr>
						<td class="print-redemption-label">Created date:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->exchange_date; ?></td>
					</tr>
					<tr>
						<td class="print-redemption-label">Created by:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->created_by; ?></td>
					</tr>
					<?php if(!empty($this->models[0]->updated_by)): ?>
					<tr>
						<td class="print-redemption-label">Updated date:</td>
						<td class="print-redemption-value"><?php echo strtotime($this->models[0]->updated_date)?date("d-m-Y H:i:s",strtotime($this->models[0]->updated_date)) : ""; ?></td>
					</tr>
					<tr>
						<td class="print-redemption-label">Updated by:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->updated_by; ?></td>
					</tr>
					<?php endif;?>	
					<tr>
						<td class="print-redemption-label">Pick Up Date:</td>
						<td class="print-redemption-value"><?php echo $this->models[0]->pick_up_date; ?></td>
					</tr>
					<tr>
						<td class="print-redemption-label">Status:</td>
						<td class="print-redemption-value">
							<?php 
								//$status = JHTML::_('wrd.statusRedemptionRaw');
								//echo $status[$this->models[0]->status_of_redemption];
                            if($this->models[0]->approved == 1) : 
                                echo 'Approve';
                            elseif($this->models[0]->approved == 0) :
                                echo 'Waiting';
                            elseif($this->models[0]->approved == 2) :
                                echo 'UnApproved';
							elseif($this->models[0]->approved == 9) :
                                echo 'Deleted by us';	
                            endif;
                        
							?>
						</td>
					</tr>
                    <tr valign="top">
                        <!--<td class="print-redemption-label">Products:</td>-->
                        <td colspan="2">
                            <table cellspacing="0" cellpadding="0" style="width: 100%;">
                                <thead>
                                    <tr  class="active" style="display: table-row;background: #e6e6e5;">
                                        <th style="text-align: center;" class="product-redemption-label">Product Name</th>
										<th style="text-align: center;" class="product-redemption-label">Quantity</th>
                                        <th style="text-align: center;" class="product-redemption-label">Voucher Code</th>
										<th style="text-align: center;" class="product-redemption-label">Expired Date</th>
                                        <th style="text-align: center;" class="product-redemption-label">Type Redemption</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                        $totalPoint = 0;
                                        $totalCash = 0;
										$i=1;
										//echo '<pre>';print_r($this->models);
                                        foreach($this->models as $item):
											$code = $item->code;
                                            $idr .= $item->id.",";
                                            $product_arr = unserialize($item->product);
                                            $product = $product_arr['en-GB'];
											echo '
                                                <tr>
                                                    <td class="product-redemption-label" style="width: 22%;">'.$product.'</td>
                                                    <td class="product-redemption-label" style="text-align: center; width:10%;">'.$item->quantity.'</td>
													<td class="product-redemption-label" style="text-align: center;width:20%;">';
													
													if($item->voucher){
														echo '<input size="30" type="text" class="voucherlist" id="product_list_'.$item->id.'_voucher" rel="'.$item->id.'" onchange="updateVoucherList('.$item->id.')" name="product_list_'.$item->id.'_voucher" value="'.$item->code_voucher.'" />';													
														echo '<input type="hidden" name="idr'.$item->id .'" value="'.$item->idrv .'" />';
													}
													echo '<input type="hidden" name="product'.$item->id.'" value="'.$item->product_id .'" />';
													echo '</td>';
													
													echo '<td style="width: 26%;" class="product-redemption-label">';
												
													echo '<div style="" class="e'.$i.'">';
														$date =  ($item->expired == '0000-00-00')?"0000-00-00":date("d-m-Y",strtotime($item->expired));
														echo '<input value="'.$date.'" name="product_list_'.$item->id .'_date" type="text" id="datepicker'.$i.'" class="datepicker" rel="'.$i.'" />';
													
													echo '</div>';
														
                                                   
													echo '</td><td style="width: 15%;" class="product-redemption-label">
                                                        '.($item->cash > 0 ? 'Point: '.$item->point.'. Cash: '.number_format($item->cash, 2, '.', ',') : 'Point: '.$item->point).'
                                                    </td>
                                                </tr>
                                            ';
                                            $totalPoint += $item->point;
                                            $totalCash += $item->cash;
											$i++;
                                        endforeach;
										echo "<input type='hidden' id='voucher_id' name='voucher_id' value='".$idr ."' />";
										echo "<input type='hidden' id='product_quantity' name='product_quantity__' value='".count($this->models)."' />";
                                    ?>
                                </tbody>
                            </table>
                        </td>
                    </tr>
					<tr valign="top">
						<!--<td class="print-redemption-label">Transaction:</td>-->
						<td colspan="2">
							<table cellspacing="0" cellpadding="0" style="width: 100%;">
								<thead>
									<tr class="active" style="display: table-row;background: #e6e6e5;">
										<th style="text-align: center;" class="product-redemption-label">ID Transaction</th>
										<th style="text-align: center;" class="product-redemption-label">Outlet</th>
										<th style="text-align: center;" class="product-redemption-label">Used Point</th>
										<th style="text-align: center;" class="product-redemption-label">Percentage</th>
									</tr>
								</thead>
								<tbody>
									 <?php 
								
								$tmp_tr = array();
								
									//prepair content
									foreach ($this->tr as $key => $row) {
										//print_r($this->tr);
										$tmp_tr[$row->poulet][data][] = $row;
										$tmp_tr[$row->poulet][total] = abs($row->point) + $tmp_tr[$row->poulet][total];
										$tmp_tr[$row->poulet][outlet] = $row->name;
										$tmp_tr[$row->poulet][outletid] = $row->poulet;
									}
									?>
									<?php $total = 1; foreach($tmp_tr as $k=>$row):  ?>
									<tr style="background: #f2f2f2;">
										<td class="product-redemption-label" style="text-align: center">
											<span class="viewdetailredemption" 
											id="outlet_<?php echo $row[outletid]; ?>" 
											style="cursor: pointer">
											<small>View Detail</small></span>
										</td>
										<td class="product-redemption-label">
											<?php echo $row[outlet]; ?>
										</td>
										<td class="product-redemption-label">
											<?php echo $row[total]; ?>
										</td>
										<td class="product-redemption-label">
											<?php echo number_format(($row[total]/$totalPoint)*100,2, '.', ',') ?>%
										</td>
									</tr>
										<?php foreach($row[data] as $data_line):  ?>
											<tr class="poutlethidden outlet_<?php echo $data_line->poulet; ?>" style="display: none; ">
												<td class="product-redemption-label" style="text-align: right">
													<?php echo $data_line->transaction; ?></td>
												<td class="product-redemption-label">
													<?php 
														$db = JFactory::getDbo();
														$sql = "SELECT des,MIN(id),type FROM #__wrd_point WHERE transaction=".$data_line->transaction;
														
														$db->setQuery($sql);
														$des = $db->loadObject();
														if($des->type == 1)
															echo $des->des;
														elseif($des->type == 2)
															echo $des->des != 'Point Adjustment' ? 'Point Adjustment - '.$des->des: '';
														elseif($des->type == 0)
															echo $row[outlet];
														else
															echo 'Contact Web Team';
														
													?>
													</td>
												<td class="product-redemption-label">
													<?php echo abs($data_line->point); ?></td>
												<td class="product-redemption-label"></td>
											</tr>
										<?php endforeach; ?>
									<?php endforeach; ?>
									<?php 
									 /*
										foreach($this->tr as $item):
											echo '
												<tr>
													<td class="product-redemption-label" style="width: 23%;">'.$item->transaction.'</td>
													<td class="product-redemption-label" style="width:37%;">';
														if($item->name != ''){
															echo $item->name;
														} 
														else if(($item->type == 9) && ($item->transaction == 0)){
															echo "WMCRewards - Start Point";
														}
														else if(($item->type == 0) &&($item->transaction == 0)){
															echo "WMCRewards";
														}
														else {
															$db = JFactory::getDbo();
															if(empty($item->name)){
																$sql = "SELECT des,MIN(id) FROM #__wrd_point WHERE transaction=".$item->transaction;
																$db->setQuery($sql);
																$des = $db->loadObjectList();
																echo "WMC GROUP - ".$des[0]->des;
															}
														}
													echo '</td>
													<td class="product-redemption-label" style="width:23%;">
														'.substr($item->point,1).'
													</td>
													<td class="product-redemption-label">
														'.number_format((substr($item->point,1)/$totalPoint)*100,2, '.', ',').'%
												  
													</td>
												</tr>
											';
										   
										endforeach;
									*/	
									?>
								</tbody>
							</table>
						</td>
            </tr>
                    <tr>
                        <td class="print-redemption-label" style="">Total:</td>
                        <td class="print-redemption-value" style="font-weight: bold;">
                            <?php  
                                echo ($totalPoint > 0 ? 'Point: '.$totalPoint : '');
                                echo ($totalCash > 0 ? ' Cash: '.number_format($totalCash, 2, '.', ',') : '');
                            ?>
                        </td>
                    </tr>     
                    
                                          
                </tbody>
            </table>
            <table cellpadding="0" cellspacing="0">
                <tbody>
                    <tr>
                        <td class="key">
                            <label for="title">Outlet pick up:</label>
                        </td>
                        <td colspan="2">
                            <?php echo $this->lists['filter_pick_up_outlet']; ?>
                        </td>
                    </tr>        
                    <tr>
                        <td class="key">
                            <label for="title">Requested Outlet:</label>
                        </td>
                        <td colspan="2">
                            <?php echo $this->lists['requested_outlet']; ?>
                        </td>
                    </tr>                                       
                   
                    <tr>
                        <td class="key">
                            <label for="title">Deliver to outlet Date:</label>
                        </td>
                        <td colspan="2">
                            <?php
                                echo JHTML::_ ( 'calendar', ($this->lists['filter_deliver_date'] != '' ? $this->lists['filter_deliver_date'] : ''), 'deliver_date', 'deliver_date', '%Y-%m-%d');
                            ?>
                        </td>
                    </tr>
                    
                    <tr>
                        <td class="key">
                            <label for="title">Pick Up Date:</label>
                        </td>
                        <td colspan="2">
                            <?php
                                echo JHTML::_ ( 'calendar', ($this->lists['filter_pick_up_date'] != '' ? $this->lists['filter_pick_up_date'] : ''), 'pick_up_date', 'pick_up_date', '%Y-%m-%d');
                            ?>
                        </td>
                    </tr>
                         
                    <tr>                        
                        <td align="left" colspan="3">
                            <div style="margin: 20px 0 0; text-align: left; padding: 0 0 0 124px;">
                                <a class="ui-state-default ui-corner-all special-link" onclick="checkStatus();" id="update_transaction" style="cursor: pointer; padding-right: 20px;">Update</a>
                                <a class="ui-state-default ui-corner-all special-link" href="index.php?option=com_wrd&controller=profile&id=<?php echo intval($_GET['id']) ?>&layout=form&tab=redemption" style="cursor: pointer; padding-right: 20px;">Cancel</a>
								<a class="ui-state-default ui-corner-all special-link" href="index.php?option=com_wrd&controller=profile&layout=printredemption&code=<?php echo $code; ?>" style="cursor: pointer; padding-right: 20px;">Print Preview</a>
                                <input type="submit" value="" style="width: 0; height: 0; border: none; background: none;" />
                            </div>       
                        </td>
                    </tr>
                </tbody>
            </table>        
        </fieldset>
        
    </div>
	
    <?php if(!empty($this->user_info)):?>
    <div id="stats" style="float:right;width:25%">
        <?php
            jimport('joomla.html.pane');
            $pane =& JPane::getInstance('Tabs');
                echo $pane->startPane('myPane');
                echo $pane->startPanel(JText::_('User Infomation'), 'infotab');
                ?>
                    <table>
                        <tr>
							<td><?php echo JText::_('Member ID') ;?></td>
							<td>:</td>
							<td><strong>
								<?php
									if(!empty($this->user_info->member_id)){
										echo $this->user_info->member_id;
									}
								?> 
								</strong>
							</td>
						</tr>
						<tr>
                            <td><?php echo JText::_('Name') ;?></td>
                            <td>:</td>
                            <td><strong>
                                <?php
                                    if(!empty($this->user_info->f_name) || !empty($this->user_info->l_name)){
                                        $guest_name = $this->user_info->f_name." ".$this->user_info->l_name ;
                                    }else{
                                        $guest_name = '' ;
                                    }
                                    echo empty($guest_name)? '' : $this->user_info->prefix.' '.$guest_name ; 
                                ?> 
                           </strong> </td>
                        </tr>
						<tr>
							<td><?php echo JText::_('Mobile') ;?></td>
							<td>:</td>
							<td>
								<?php
									
									if(!empty($this->user_info->phone)){
										echo $this->user_info->phone;
									}
									else if(!empty($this->user_info->referer_phone)){
										echo $this->user_info->referer_phone;
									}
									else {
										echo "User have not mobiphone";
									}
								?>	
							</td>
						</tr>
                        <tr>
                            <td><?php echo JText::_('Date of Birth') ;?></td>
                            <td>:</td>
                            <td>
                                <?php
                                    echo empty($this->user_info->dob) ? '' : date("d-m-Y",strtotime($this->user_info->dob)); 
                                ?> 
                            </td>
                        </tr>
                        <tr>
                            <td><?php echo JText::_('Job Title') ;?></td>
                            <td>:</td>
                            <td>
                                <?php  echo empty($this->user_info->o_job) ? '' : $this->user_info->o_job ; ?> 
                            </td>
                        </tr>
                        <tr>
                            <td><?php echo JText::_('Member Joining Date') ;?></td>
                            <td>:</td>
                            <td>
                                <?php
                                    echo empty($this->user_info->created_date) ? '': date("d-m-Y",strtotime($this->user_info->created_date)); ; 
                                ?> 
                            </td>
                        </tr>
						<?php if(!empty($this->outlet->name)): ?>
                        <tr>
                            <td><?php echo JText::_('Outlet') ;?></td>
                            <td>:</td>
                            <td>
                                <?php
                                    echo empty($this->outlet->name) ? '' : $this->outlet->name ; 
                                ?> 
                            </td>
                        </tr>
						<?php endif;?>
                        <tr>
                            <td><?php echo JText::_('Current points balance') ;?></td>
                            <td>:</td>
                            <td>
                                <?php echo number_format($this->user_info->p_o_u,0,".",".") ; ?> 
                                <input type="hidden" name='p_o_u' id='p_o_u' value='<?php echo $this->user_info->p_o_u ;?>' />
                            </td>
                        </tr>
						<tr>
                            <td><?php echo JText::_('Total spending') ;?></td>
                            <td>:</td>
                            <td>
                                <?php echo number_format($this->user_info->total_spend,0,".","."); ?> 
                            </td>
                        </tr>
                    </table>
                <?php 
                echo $pane->endPanel();
            
            echo $pane->endPane();
        ?>
    </div>
    <?php endif ; ?>
    <div id="stats" style="float:right;margin: 10px 0 ; width:40%">
        <div id='product_info'>&nbsp;</div>
    </div>
    <input type="hidden" name="updated_by" value="<?php echo $user->id;?>" />
	<input type="hidden" name="approved" value="<?php echo $this->models[0]->approved;?>" />
	<input type="hidden" name="controller" value="profile" />
    <input type="hidden" name="option" value="com_wrd" />
    <input type="hidden" name="uid" value="<?php echo (int)$this->user_info->user_id; ?>" />
    <input type="hidden" name="codeverify" value="<?php echo strval($_GET['code']); ?>" />
    <input type="hidden" name="redemption_user_id" value="<?php echo intval($_GET['id']); ?>" />
    <input type="hidden" name="layout" value="updateredemption" />
    <?php echo JHTML::_( 'form.token' ); ?>
</form>
<input type="hidden" id="current-product-id">
<!-- ui-dialog -->
<div id="dialog" title="Product details">
    <div class="dialog-content">
        
    </div>
</div>
